package userlogic

import (
	"OemServer/internal/svc"
	"OemServer/pb"
	"common/dao/model"
	comJwt "common/jwt"
	"common/utils"
	"context"
	"errors"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	"time"
)

type PointLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPointLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PointLogic {
	return &PointLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PointLogic) Point(in *pb.UserPint) (*pb.Emp, error) {
	// todo: add your logic here and delete this line
	if in.Way != 1 && in.Way != 0 {
		return nil, errors.New("way 0 or 1")
	}
	if in.Point == 0 {
		return nil, errors.New("point is Greater than 0")
	}
	if in.UserUuid == "" {
		return nil, errors.New("user uuid is empty")
	}
	jwtUser, err := comJwt.BackUser(l.ctx, l.svcCtx.Config.USERDATA)
	if err != nil {
		return nil, err
	}
	var (
		inUser    model.User
		nowUser   model.User
		pointInfo model.PointInfo
		text      string
	)
	db := l.svcCtx.DB
	table := db.Table(model.TableNameUser)
	if err := db.Table(model.TableNameUser).Where("uuid = ?", in.UserUuid).First(&inUser).Error; err != nil {
		return nil, err
	}
	if err := db.Table(model.TableNameUser).Where("uuid = ?", jwtUser.UUID).First(&nowUser).Error; err != nil {
		return nil, err
	}
	pointTable := db.Table(model.TableNamePointInfo)
	err = pointTable.Transaction(func(tx *gorm.DB) error {

		if in.Way == 1 {
			text = "加上"
			inUser.Points += in.Point
		} else if in.Way == 0 {
			text = "减去"
			inUser.Points -= in.Point
		}
		if err1 := table.Updates(&inUser).Where("uuid = ?", inUser.UUID).Error; err1 != nil {
			return err1
		}
		t := time.Now()
		pointInfo.CreateTime = &t
		pointInfo.UUID = utils.GetUuid()
		pointInfo.OperateUserUUID = jwtUser.UUID
		pointInfo.UserUUID = inUser.UUID
		pointInfo.Point = in.Point
		pointInfo.PointWay = in.Way
		pointInfo.PointRoom = in.RoomUuid
		pointInfo.PointInformation = fmt.Sprintf("操作人员 %s(%s) 给 %s(%s) %s %d 分", nowUser.Account, nowUser.UUID, inUser.Account, inUser.UUID, text, in.Point)
		if err := tx.Create(&pointInfo).Error; err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		return nil, err
	}
	return &pb.Emp{}, nil
}
